package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"handler/operate"
)

type TagPushHook struct {
	Ref          string         `json:"ref"`
	CheckoutSha  string         `json:"checkout_sha"`
	UserName     string         `json:"user_name"`
	UserUsername string         `json:"user_username"`
	UserEmail    string         `json:"user_email"`
	FaasEnv      string         `json:"faas_env"`
	Project      *Project       `json:"project"`
	ImageName    string         `json:"image_name"`
	FuncName     string         `json:"func_name"`
	Config       *config.Config `json:"config"`
	OpenFaasUrl  string         `json:"open_faas_url"`
}

type Project struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	GitHttpUrl  string `json:"git_http_url"`
	Namespace   string `json:"namespace"`
}

func main() {
	var err error
	input, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatalf("Unable to read standard input: %s", err.Error())
	}
	var tagPushHook TagPushHook
	err = json.Unmarshal(input, &tagPushHook)
	if err != nil {
		log.Println("Executing parse json:", err)
		return
	}
	fmt.Println(input)
	os.Setenv("DOCKER_HOST", "tcp://192.168.1.250")
	os.Setenv("docker_remote_host", os.Getenv("DOCKER_HOST"))
	fmt.Println("TAG = ", os.Getenv("TAG"))
	fmt.Println("FAAS_ENV = ", os.Getenv("FAAS_ENV"))
	fmt.Println("OPENFAAS_URL = ", os.Getenv("OPENFAAS_URL"))
	fmt.Println("DOCKER_HOST = ", os.Getenv("DOCKER_HOST"))
	fmt.Println("PROJECT_NAME = ", os.Getenv("PROJECT_NAME"))
	fmt.Println("docker_remote_host = ", os.Getenv("docker_remote_host"))


	err = operate.LoginFaas()
	operate.RecordProcess("1", "login faas", err)
	if err != nil {
		log.Fatalln(err)
		return
	}
	err = operate.LoginDocker()
	operate.RecordProcess("2", "login docker", err)
	if err != nil {
		log.Fatalln(err)
		return
	}
	err = operate.CloneCode()
	operate.RecordProcess("3", "clone code", err)
	if err != nil {
		log.Fatalln(err)
		return
	}
	err = operate.BuildCode()
	operate.RecordProcess("4", "build code", err)
	if err != nil {
		log.Fatalln(err)
		return
	}
	err = operate.PushImage()
	operate.RecordProcess("5", "push image", err)
	if err != nil {
		log.Fatalln(err)
		return
	}
	err = operate.DeployImage()
	operate.RecordProcess("6", "deploy image", err)
	fmt.Println(err.Error())
	if err != nil {
		log.Fatalln(err)
		return
	}
}
